package com.iflytek.filter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器,拦截所有的请求，除了login页面，和/user/login(一个意思)
 * 请求中的session包含用户信息的就放行，否则返回登陆页面(回退，重加载)
 */
public class LoginIntercept implements HandlerInterceptor {
    // 这个方法很重要
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //先得到session,在看他为不为空
        //注意httpServletRequest 中的h是小写
        HttpSession session = httpServletRequest.getSession();
        Object userInfo = session.getAttribute("userInfo"); // 在UserController中 login 方法中 放入了（保存会话session的）userInfo
        // 只需要判断不为空就可以了
        if (userInfo != null){
            //该请求是登录过的
            // 直接放行
            return true;
        }else {
            //未登录，跳转登陆页面
            // 重定向到登录页面
            httpServletResponse.sendRedirect("/employ_management_war_exploded/login.jsp");
            return false;
        }
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

